package com.web.servlet;



import com.alibaba.fastjson2.JSON;
import com.web.JBDCUtils;
import com.web.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {

    public HelloServlet(){
        System.out.println("HelloServlet instance");
    }

    @Override
    public void init() throws ServletException {
        System.out.println("HelloServlet init");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
        System.out.println("HelloServlet service");
    }

    @Override
    public void destroy() {
        System.out.println("HelloServlet destroy");
    }



    //处理get请求
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求编码
        req.setCharacterEncoding("UTF-8");
        //设置响应编码
        resp.setCharacterEncoding("UTF-8");
        //获得请求参数
        String name=req.getParameter("name");
        String age=req.getParameter("age");
        System.out.println("name:"+name+"age:"+age);
        //给浏览器返回一行数据
        List<Student> list = JBDCUtils.query(Student.class,"select*from student");
        String str = JSON.toJSONString(list);
        //响应流发送数据给用户
        resp.getWriter().write(str);

        //重定向
       // resp.sendRedirect("http://www.baidu.com");

    }
}
